<template>
  <el-dialog title="分配权限" :visible="isShowDiaglog" @close="closeFn">
    <el-tree
      ref="tree"
      :data="permissionList"
      :props="{label: 'title'}"
      show-checkbox
      check-strictly
      node-key="id"
      default-expand-all
    />
    <template #footer>
      <el-row type="flex" justify="center">
        <el-button size="small" type="primary" @click="saveFn">保存</el-button>
        <el-button size="small" @click="closeFn">取消</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { getPermissions } from '@/api/permissions'
import { getRoleDetail, EditRole } from '@/api/roles'
export default {
  props: {
    isShowDiaglog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      roleDetail: [],
      // 权限列表
      permissionList: [],
      // 角色权限id
      perIdList: []
    }
  },
  created() {
    this.getPermissionsList()
  },
  methods: {
    // 保存--编辑角色权限
    async saveFn() {
      this.roleDetail = {
        ...this.roleDetail,
        permissions: this.$refs.tree.getCheckedNodes()
      }
      console.log(this.roleDetail)
      await EditRole(this.roleDetail)
      this.$message.success('分配权限成功')
      this.$emit('update:isShowDiaglog', false)
      // // 刷新
      this.$emit('updateEvent')
    },
    // 关闭
    closeFn() {
      this.getPermissionsList()
      this.$emit('update:isShowDiaglog', false)
    },
    // 获取权限列表
    async getPermissionsList() {
      const res = await getPermissions()
      // console.log(res)
      this.permissionList = this.listToTree(res.data, '0')
    },
    // 格式化权限列表为树形结构
    listToTree(arr, id) {
      // type: '1'表示为一级权限，'2'为二级权限
      const list = []
      arr.forEach((item) => {
        if (Number(item.pid) === Number(id)) {
          // item.children = this.listToTree(arr, item.id)
          item.children = this.listToTree(arr, item.id)
          list.push(item)
        }
      })
      // console.log('list', list)
      return list
    },
    // 根据id获取角色详情--回显角色权限列表
    async getRolePerById(id) {
      const res = await getRoleDetail(id)
      // console.log(res)
      // 保存角色详情
      this.roleDetail = res.data
      console.log(this.roleDetail)
      // 设置勾选中的权限节点 -- 回显
      this.$refs.tree.setCheckedNodes(this.roleDetail.permissions)
    }
  }
}
</script>

<style>
</style>
